package com.ruoyi.web.controller.system;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.wx.WxVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wx")
public class WxController extends BaseController {

    private static final String APPID = "wx9b3f44e3a62269b5";
    private static final String SECRET = "d27cb0595154ce78c90231f4e1bc635f";
    private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    private static String AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE#wechat_redirect";


    @GetMapping("/auth-url")
    public AjaxResult authUrl(WxVo wxVo) {
        AjaxResult ajax = new AjaxResult();
        System.out.println("redirectUri = " + wxVo.getRedirectUri());
        String authUrl = AUTH_URL.replace("APPID", APPID).replace("REDIRECT_URI", wxVo.getRedirectUri()).replace("SCOPE", wxVo.getScope());
        ajax.put("authUrl", authUrl);
        ajax.put("code", 200);
        System.out.println(authUrl);
        return ajax;
    }

    @GetMapping("/user-info")
    public AjaxResult userInfoUrl(WxVo wxVo) {
        AjaxResult ajax = new AjaxResult();
        System.out.println(wxVo.getCode());
        String userUrl = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("SECRET", SECRET).replace("CODE", wxVo.getCode());
        String response = HttpUtil.get(userUrl);
        JSONObject entries = JSONUtil.parseObj(response);
        System.out.println(entries);
        String openid = entries.getStr("openid");
        System.out.println(openid);
        ajax.put("openid", openid);
        ajax.put("code", 200);
        return ajax;
    }


}
